package com.google.bling.client.widget;

import com.google.bling.client.Util;
import com.google.bling.client.widget.PerUserAmountWidget.Listener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Displays a list of labeled text boxes.
 *
 * @author koz@google.com (James Kozianski)
 *
 */
public class ExpenseRetrievalGrid extends Composite {
  private HorizontalPanel panel = new HorizontalPanel();
  private Chart chart = new Chart();
  private List<PerUserAmountWidget> perUserAmounts = Util.list();
  private final List<String> names;
  private PerUserAmountTotalWidget totalWidget;

  public ExpenseRetrievalGrid(List<String> names) {
    this.names = names;
    initWidget(panel);
    clearInput();
  }

  public Map<String, Integer> getAmounts() {
    Map<String, Integer> result = new HashMap<String, Integer>();
    for (PerUserAmountWidget w : perUserAmounts) {
      result.put(w.getUserName(), w.getAmount());
    }
    return result;
  }

  public void clearInput() {
    panel.clear();
    perUserAmounts.clear();
    panel.add(new PerUserAmountKeyWidget());
    for (String name : names) {
      PerUserAmountWidget w = new PerUserAmountWidget(name, 0, 0, 100 / names.size());
      perUserAmounts.add(w);
      panel.add(w);
      w.setListener(new Listener() {
        public void onChanged() {
          onPerUserAmountChanged();
        }
      });
    }
    totalWidget = new PerUserAmountTotalWidget();
    panel.add(totalWidget);
    totalWidget.setAmount(0);
    totalWidget.setPercent(100);
    panel.add(chart);
  }

  protected void onPerUserAmountChanged() {
    recalculateTotal();
  }

  private void recalculateTotal() {
    int amountTotal = 0;
    int percentTotal = 0;
    for (PerUserAmountWidget w : perUserAmounts) {
      amountTotal += w.getAmount();
      percentTotal += w.getPercent();
    }
    totalWidget.setAmount(amountTotal);
    totalWidget.setPercent(percentTotal);
    chart.setData(getAmounts());
  }

  public void setTotalAmount(int i) {
    for (PerUserAmountWidget w : perUserAmounts) {
      w.setTotalAmount(i);
    }
  }
}
